/**
 * Anderground project - Subway maps processor application.
 * Copyright (C) 2008-2009 Eldar Abusalimov, Ilya Shurigyn
 * 
 * This file is part of Anderground.
 * 
 * Anderground is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * Anderground is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Anderground.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.anderground.modules.storage;

import java.io.IOException;

import org.anderground.core.storage.DataWriter;
import org.anderground.core.storage.StorageException;

/**
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 * @param <T>
 *            data type
 * @param <Out>
 *            the destination to write the data to
 */
public abstract class AbstractWriter<T, Out> extends AbstractIOWrapper<Out>
		implements DataWriter<T> {

	@Override
	public final void write(T data) throws IOException {
		if (data == null) {
			throw new StorageException("cannot write null data");
		}
		Out out = openIO();
		if (out == null) {
			throw new StorageException("openIO has returned null");
		}
		try {
			writeToOutput(data, out);
		} finally {
			if (shouldCloseIOAfterComplete()) {
				closeIO(out);
			}
		}
	}

	/**
	 * Implementation should write the data to the specified Output.
	 * 
	 * @param data
	 *            the data to write (if anything goes wrong a
	 *            {@link IOException} should be thrown instead of silently
	 *            ignoring writing failure)
	 * @param out
	 *            the output to write to
	 * 
	 * @throws IOException
	 *             (possibly wrapping another exception) if an I/O error occurs
	 */
	protected abstract void writeToOutput(T data, Out out) throws IOException;

}
